<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/6 23:20
 */

namespace module\ai\library\channel\llm;

use module\ai\library\channel\abstract\Llm;
use module\ai\library\channel\completion\XunfeiCompletion;
use module\ai\library\channel\interface\CompletionInterface;
use Psr\Http\Message\ResponseInterface;

class XunfeiSpark extends Llm
{
    protected string $baseUrl = 'https://spark-api-open.xf-yun.com/v1/chat/completions';

    /**
     * @inheritdoc
     */
    public static function versions(): array
    {
        return [
            'lite'        => 'Spark Lite (免费)',
            'generalv3'   => 'Spark Pro (免费)',
            'pro-128k'    => 'Spark Pro-128K',
            'generalv3.5' => 'Spark Max',
            'max-32k'     => 'Spark Max-32K',
            '4.0Ultra'    => 'Spark Ultra'
        ];
    }

    /**
     * @inheritdoc
     */
    public function setPayload(array $config, $override = false): void
    {
        parent::setPayload($config, $override);

        $keys = [
            'temperature', 'top_p', 'max_tokens', 'tools', 'tool_choice',
        ];
        foreach ($keys as $key) {
            if (isset($config[$key]) && strlen($config[$key]) > 0) {
                $this->payload[$key] = $config[$key];
            }
        }
    }

    /**
     * @inheritdoc
     */
    protected function getResponse(bool $isStream = false, array $clientOptions = []): ResponseInterface
    {
        return parent::getResponse($isStream, [
            'headers' => [
                'Authorization' => vsprintf("Bearer %s:%s", [
                    $this->getKeyModel()?->config['api_key'],
                    $this->getKeyModel()?->config['secret_key'],
                ]),
            ]
        ]);
    }

    /**
     * @inheritdoc
     */
    protected function getCompletionStruct(array $data, bool $isStream = false): ?CompletionInterface
    {
        return new XunfeiCompletion($data, $isStream);
    }

}